package com.andy.qhb.entity;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import com.andy.qhb.dao.DaoUtils;
import com.andy.qhb.dao.vo.Where;
import com.andy.qhb.game.GameUser;
import com.andy.qhb.game.GlobalHttp;
import com.andy.qhb.utils.GoConstant;
import com.andy.qhb.utils.JsonUtils;
import com.andy.qhb.vo.GroupConfig;
import com.andy.qhb.vo.HFriend;
import com.google.common.collect.Lists;

public class UsrGroups extends BaseEntity{

	private static final long serialVersionUID = 1L;

	public UsrGroups() {
	}
	
	public UsrGroups(Long id) {
		super(id);
	}
	
	private Long cid;
	private String name;
	private String guids;
	private String remark;

	public static String table() {
		return "usr_groups";
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getGuids() {
		return guids == null?"":guids;
	}

	public void setGuids(String guids) {
		this.guids = guids;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
		this.config = null;
	}
	
	private List<HFriend> members;
	public List<HFriend> members(){
		if(members == null){
			members = Lists.newArrayList();
			if(guids != null){
				List<Map<String, Object>> list = DaoUtils.getListSql("select id,nick_name,icon from usr_user where id in (?)", guids);
				list.forEach((it)->{
					members.add(new HFriend(MapUtils.getLong(it, "id"),MapUtils.getString(it, "nick_name"),MapUtils.getString(it, "icon")));
				});
			}
		}
		
		return members;
	}
	
	public boolean addMember(Long uid,String name,String icon) {
		if(getGuids().indexOf(uid+",") >= 0){
			return false;
		}
		this.guids = getGuids() + uid+",";
		members().add(new HFriend(uid, name,icon));
		return true;
	}
	
	public void remove(Long uid) {
		guids = StringUtils.remove(guids, uid+",");
		members.remove(new HFriend(uid, null,null));
	}

	public Long getCid() {
		return cid;
	}

	public void setCid(Long cid) {
		this.cid = cid;
	}
	
	private GameUser creater;
	public GameUser creater() {
		if(creater == null) {
			creater = GlobalHttp.getUser(cid);
		}
		return creater;
	}
	
	private List<UsrMsgLog> rlogs;
	public List<UsrMsgLog> rlogs(){
		if(rlogs == null) {
			rlogs = DaoUtils.getList(UsrMsgLog.class, Where.eq("uid_other", getId()),
					Where.eq("type", GoConstant.MSG_1),
					Where.eq("status", 0));
		}
		return rlogs;
	}
	
	private GroupConfig config;
	public GroupConfig config() {
		if(config == null) {
			config = JsonUtils.fromJson(remark, GroupConfig.class);
		}
		return config;
	}
	

}
